/*
 * @lc app=leetcode.cn id=24 lang=golang
 *
 * [24] 两两交换链表中的节点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}
	if head.Next == nil {
		return head
	}

	node := &ListNode{Val: -1, Next: nil}
	ptr := node
	for head != nil {
		first, second := swapTwo(head)
		if second != nil {
			head = second.Next
		} else {
			head = nil
		}

		ptr.Next = first
		ptr = second
	}
	return node.Next
}
func swapTwo(head *ListNode) (*ListNode, *ListNode) {
	if head == nil {
		return nil, nil
	}
	if head.Next == nil {
		return head, nil
	}
	next := head.Next
	head.Next = next.Next
	next.Next = head
	return next, head
}

// @lc code=end

